package com.lninl.controller;

import com.lninl.model.Tag;
import com.lninl.model.Uri;
import com.lninl.model.User;
import com.lninl.model.UserUri;
import com.lninl.repository.*;
import com.lninl.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.HashSet;
import java.util.Set;

@Controller
public class UserUriController {

    @Autowired
    private UserService userService;
    @Autowired
    private UriService uriService;
    @Autowired
    private TagService tagService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UriRepository uriRepository;
    @Autowired
    private TagRepository tagRepository;
    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private UserUriRepository userUriRepository;
    @Autowired
    private UserUriService userUriService;

    /**
     * 用户给链接打标签
     *
     * @param user
     * @param uri
     * @param tag
     * @return
     */
    @RequestMapping(value = "/user/{userId}/uri/{uriId}/tag/{tagId}", method = RequestMethod.POST)
    public ResponseEntity addTag(@PathVariable("userId") User user, @PathVariable("uriId") Uri uri,
                                 @PathVariable("tagId") Tag tag) {
        UserUri userUri = new UserUri();
        userUri.setUri(uri);
        userUri.setUser(user);
        Set<Tag> tags = new HashSet<>();
        tags.add(tag);
        userUri.setTags(tags);
        return new ResponseEntity<>(userUriRepository.save(userUri), HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{userId}/uri/{uriId}", method = RequestMethod.GET)
    public ResponseEntity get(@PathVariable("userId") User user, @PathVariable("uriId") Uri uri) {
        return new ResponseEntity<>(userUriRepository.findByUserIdAndUriId(user.getId(), uri.getId()), HttpStatus.OK);
    }

    @RequestMapping(value = "/user/{userId}/uri/{uriId}", method = RequestMethod.POST)
    public ResponseEntity add(@PathVariable("userId") User user, @PathVariable("uriId") Uri uri) {
        return new ResponseEntity<>(userUriService.save(user,uri), HttpStatus.OK);
    }
}
